package backpage.service.Impl;

import backpage.entity.Employee;
import backpage.entity.SalaryLevel;
import backpage.mapper.SalaryLevelMapper;
import backpage.mapper.SalarySummaryMapper;
import backpage.service.EmployeeService;
import backpage.service.SalarySummaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class SalarySummaryServiceImpl implements SalarySummaryService {

    @Autowired
    private SalarySummaryMapper salarySummaryMapper;

    @Autowired
    private SalaryLevelMapper salaryLevelMapper;

    @Autowired
    private EmployeeService employeeService;

    @Override
    public void createMonthlySalarySummary() {
        // 获取所有在职员工
        List<Employee> employees = employeeService.queryAllEmployeeInfo();
        for (Employee employee : employees) {
            if (employee.getIsActive()) {
                Integer salaryLevelId = employee.getCurrentSalaryLevel();
                SalaryLevel salaryLevel = salaryLevelMapper.selectById(salaryLevelId);
                if (salaryLevel != null) {
                    BigDecimal baseSalary = salaryLevel.getBaseSalary();
                    BigDecimal hourlySalary = baseSalary.divide(BigDecimal.valueOf(22 * 8), 2, RoundingMode.HALF_UP);

                    // 设置当前月份的第一天
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.DAY_OF_MONTH, 1);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);
                    Date month = calendar.getTime();

                    salarySummaryMapper.insertSalarySummary(
                            employee.getEmployeeId().longValue(),
                            month,
                            hourlySalary.doubleValue(),
                            baseSalary.doubleValue(),
                            0.0,
                            0.0
                    );
                }
            }
        }
    }
}